const express = require('express');
const path = require('path');
const request = require('request');
// 配置静态文件服务中间件
// server地址
const app = express();
const port = 4001;
let serverUrl = 'http://localhost:5000';
// console.log(path.join(__dirname, '../../src'));
app.use(function (req, res, next) {
  //TODO 中间件，每个请求都会经过
  console.log('---------');
  console.log(req.path);
  const filename = req.path.split('/').slice(-1)[0];
  res.append('Content-Disposition', `attachment; filename="${filename}"`);
  next();
});
app.use(express.static(path.join(__dirname, '../../src')));

//它不能放最前面，get可以。get不会冲突，use会
// app.use('/', function (req, res) {
//     res.send('hello world');
// });
// app.get('/test', (req, res) => res.send('Hello test!'));
// app.get('/', (req, res) => res.send('Hello World!'));
// app.get('/test', (req, res) => res.send('Hello test!'));

// app.use('/base/', function (req, res) {
//     let url = 'http://localhost:3000/base' + req.url;
//     req.pipe(request(url)).pipe(res);
// });
app.use('/test', function (req, res, next) {
    // console.log('test');
    // res.status(404).send("Sorry can't find that!");
    // throw new Error('test 404');
  // res.set({
  //   'Content-Type': 'application/octet-stream',
  //   'Content-Disposition': "attachment; filename=test.txt"
  // });
  res.type('application/octet-stream');
  res.attachment('abc.txt');
  res.send('Hello test!')
});

//
// app.use(function (err, req, res, next) {
//     //TODO 失败中间件，请求错误后都会经过
//     console.error(err.stack);
//     res.status(500).send('Something broke!');
//     next();
// });
//
// app.use('/', function (req, res) {
//     let url = serverUrl + req.url;
//     req.pipe(request(url)).pipe(res);
// });

app.listen(port, function () {
  console.info(`server started in http://localhost:${port}`);
});
